package com.leo;

import javafx.application.Platform;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @ClassName MyScheduledService
 * @Description
 * @Author wangss
 * @date 2020.06.20 22:52
 * @Version 1.0
 */
public class MyScheduledService extends ScheduledService<Number> {

    @Override
    protected Task<Number> createTask() {
        Task<Number> task = new Task<Number>() {
            @Override
            protected Number call() throws Exception {
                System.out.println("是否ui主线程：" + Platform.isFxApplicationThread() + ", " + Thread.currentThread().getName());

                FileInputStream fis = new FileInputStream(new File("D:\\log\\123.jpg"));
                double fileSize = fis.available();
                byte[] bytes = new byte[1024];
                int read = 0;
                double readSize = 0;
                double progress = 0;

                FileOutputStream fos = new FileOutputStream(new File("D:\\log\\2.jpg"));

                this.updateTitle("拷贝");
                while ((read = fis.read(bytes, 0, bytes.length)) != -1) {

                    // 预防取消失败的情况
                    if (this.isCancelled()) {
                        break;
                    }

                    fos.write(bytes, 0, read);
                    readSize = readSize + read;
                    progress = readSize / fileSize;

                    this.updateProgress(readSize, fileSize);

                    if (progress < 0.5) {
                        this.updateMessage("请耐心等待");
                    } else if (progress < 0.8) {
                        this.updateMessage("即将完成");
                    } else if (progress < 1) {
                        this.updateMessage("就差一步");
                    } else if (progress >= 1) {
                        this.updateMessage("恭喜完成");
                    }

                    Thread.sleep(1);
                }

                fis.close();
                fos.close();

                return progress;
            }
        };
        return task;
    }
}
